package com.jiyinit.web.core.activiti.util;

import com.jiyinit.core.framework.base.util.Check;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

/**
 * Created by user1 on 2018/11/23.
 */
public class MapToEntity {

    public static <T> T mapToEntity(Map<?, ?> map, Class<T> clazz) throws Exception {
        T obj = clazz.newInstance();
        Field[] fields = clazz.getDeclaredFields();
        Set<? extends Map.Entry<?, ?>> entries = map.entrySet();
        if (Check.isNullCollection(entries)) {return obj;}
        for (int j = 0; j < fields.length; j++) {
            Field field = fields[j];
            field.setAccessible(true);
            String fname = field.getName();
            entryFor:
            for (Map.Entry<?, ?> entry : entries) {
                if (entry.getKey().equals(fname)) {
                    field.set(obj, entry.getValue());
                    break entryFor;
                }
            }
        }
        return obj;
    }
}
